Showing the share count on each article is also the social proof of you. The counts can get your readers to share even more. Creating a simple share count for each article in WordPress can be useful. We will learn how to use PHP and WordPress functions to get the counts for each of our article.

This article will be an informative one and we will look into different scenarios on how to get the information. If you are looking into how to create a sharing solution, I have covered that in another article where we learn How to Create Sharing Buttons similar to Jetpack.

You can easily implement the code in this article in the article mentioned above or in your own solution.

Share Counts in Social Media

The share count for our URL can be retrieved from several network.

We will look into:

  • Facebook
  • LinkedIN
  • Google+
  • Twitter
  • Pinterest
  • StumbleUpon

All those share counts will be saved as meta data for each article. We will schedule this process on a daily basis so that we get up-to-date counts for each article.

Problematic Social Media

Some of social media share counts are a little harder to get. Fortunately there are people working on that issues and there are solutions for them.

Twitter

The most problematic social media is Twitter. They have removed the ability to get the share count directly. Today, we need to get it by searching Twitter using their Search API.

Several services have already implemented that solution and they offer their solution for free by using their service API. We will use NewShareCounts.com to search Twitter and get our counts.

Google+

Another problematic social media is Google+. They do allow us to see the counts by using their buttons. Google+ had provided us a direct way of getting the share count, but not anymore.

I have found a solution provided by another developer at StackOverFlow.

LinkedIN

LinkedIN actually provides a nice and direct way of getting the share counts. The only problematic part is the error I got using the WordPress function wp_remote_get. It seems that using cURL or similar techniques, there is an error that states the SSLRead() has failed.

I did not invest time into researching that, but the first few results I have come upon are or WordPress relates (with cURL) or something related to OSX which I am using at the time of writing. The first result is probably also associated with the OSX.

So, instead of using that function, we will use the plain old file_get_contents.

The Base of Share Counts

Our base for share counts will be an Interface. Our classes will have to implement the methods defined in that interface. This way, we are making some mandatory methods that will be used across all the classes.

Since this is just a simple example, you could use plain functions to get everything done. The only reason I am using classes and the interface is to show you how that works together.

This is our Interface that we will implement in our classes. The only method here is get_share_count that accepts a parameter $url.

Let’s now tackle the social media to get our share counts!

Facebook

Edited 16.11.2016

To get the share counts from Facebook, we have to use their own Graph API. In this tutorial, we will fetch the data using the version 2.7 on the link https://graph.facebook.com/v2.7/. You can use also the version 2.8 since everything is the same for this data.

First we must specify our own Facebook App ID and Secret which can be found in one of your Facebook Applications. If you don’t have one, create it.

Here we have encoded our $url and set it to the parameter id. We have also set the data we request by using the parameter fields. For better understanding on how to use the Graph API you should check the Facebook Developer Docs. We have also appended the parameter access_token. This access_token is created by combining the Facebook App ID and Secret. Generating access tokens can be done in different ways, but since we are using an application we are using the App Access Token.

Once our request URL has been built, we sending a GET request using the function wp_remote_get. Since that function will return a set of responses, we are also using the function wp_remote_retrieve_body to get only the body of that response where all the data resides.

The response is in JSON, so we are decoding it into an array. After that we are getting the value under the key share_count which resides in another array share.

Twitter

Our first problematic social media when it comes to retrieve the share counts. As I have mentioned earlier, we will use another service for that.

In this method we are simply retrieving the data using the URL http://public.newsharecounts.com/count.json and the parameter url.

The data is then decoded from JSON to Array. The share count is then easily retrieved using the key count.

Google+

Another problematic social media! For this one, we will not use any WordPress functions. It was possible before, but now we will have to get the whole HTML from the Google+ share button and then read the HTML and get the text which references the share count.

Here we are getting the complete HTML for that button. Since that is an HTML provided by Google+, it will have also some JavaScript there and so we are stripping everything from it. Once everything has been stripped and the $match is filled with values, the variable $match will be an Array like this:

Array ( 
   => Array ( 
     => window.__SSR = {c: 4. 
     => 4 ) )

We are then getting the count 4 by using $match.

LinkedIN

The LinkedIN is the last one that can cause some trouble when working with it. It is actually the simplest one. The URL to retrieve the count is https://www.linkedin.com/countserv/count/share.

The parameters are as in Facebook:

  • url
  • format

We are getting the data using the plain function file_get_contents and decoding the JSON into an Array/code>.

Pinterest

Pinterest has a trick also. Their URL to retrieve the share count is: http://api.pinterest.com/v1/urls/count.json. We also need to provide two parameters:

  • url
  • callback – callback is something that is used by jsonp in JavaScript.

Because of the callback parameter, we had to set a value. The value is a fixed one pin. Now our response will be pin(json_we_need).

To strip the wrapper, we are using the simple function str_replace. Once we have done that, we will have a value that can be decoded from JSON to Array.

The last part is to return the share count value that resides under the key count.

StumbleUpon

The last, but not the least is the social media StumbleUpon. Their URL is: http://www.stumbleupon.com/services/1.01/badge.getinfo and the only parameter that is needed is url.

Their JSON is a bit different and the count is actually residing under the key views. Their counts are actually views by other people who have stumbled upon your URL.

How to display the Share Counts

The method get_share_count is a static one. This means that we can directly call it without instantiating the object. Here is an example of all the classes on the same URL and the share counts retrieved at the time of writing:

Conclusion

When using other services, we are bound to their APIs and their decision. This bound can be great or it could cause some problems. Those problems in this situation is the retrieval of share counts for Twitter or Google+. We had to find an alternative way of getting the counts.

By using an alternative way, we can’t be sure that it will work all the time. Because of that, we should try and test those every few months.

We have also learned a bit what Interfaces are in PHP. This is a great way to define which methods have to be implemented in a class.

Have you tried to retrieve the share counts? Which plugin or service do you use for that? Please, share your experience and knowledge in the comments below.

Become a Sponsor

Posted by Igor Benic

Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic.

5 Comments

  1. Please how can i display this on each individual post on wordpress. alongside share buttons

    Reply

    1. Hi John, that depends on the share buttons you’re using. If those share buttons have a filter that would allow to hook into it and add new HTML, then we could add that there. But if not, the only way to display such share counts is to add them separately at the bottom of the content.

      This can be done by using code like this:

      add_filter( 'the_content', 'my_share_counts', 99 );
      
      function my_share_counts( $content ) {
         if( is_single() ) {
            $post_id = get_the_id();
            $url = get_permalink( $post_id );
            $content .= '<p><strong>' . __( 'Shares', 'yourtextdomain' ) . '</p></strong>';
            $content .= '<p><strong>' . __( 'Facebook:', 'yourtextdomain' ) . ' ' . FacebookShareCount::get_share_count( $url ) . '</strong> <strong>' . __( 'Twitter', 'yourtextdomain' ) . ' ' . TwitterShareCount::get_share_count( $url ) . '</strong></p>';
         }
         
        return $content;
      }
      

      Reply

  2. Hi, I think Facebook ‘share’ field is deprecated for versions v2.9 and higher. So it should be ‘&fields=engagement&access_token=’ instead of ‘&fields=engagement&access_token=’

    Great post btw!

    Reply

  3. Opps, I mean instead of ‘&fields=share&access_token=’ just use ‘&fields=engagement&access_token=’ because share_count is now under engagement based on https://developers.facebook.com/docs/graph-api/reference/v2.11/url

    Reply

    1. Thanks Robert for that! I’ll check that out and update the tutorial as soon as I can:)

      Reply

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.